﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Core.Model;
using DapperExtensions;
using DapperExtensions.Mapper;
using log4net;

namespace DataServer.Dao
{
    public class OperRecordDao : BaseDao<OperRecord>
    {
        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static OperRecordMapper _mapper;

        public OperRecordDao()
        {
            if (_mapper == null)
            {
                _mapper = new OperRecordMapper();
            }
        }

        protected override string GetTableName()
        {
            if (_mapper != null)
                return _mapper.TableName;
            return "user_oper_record";
        }

        public List<OperRecord> GetOperations(string  user,DateTime? from,DateTime? to)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicateGroup = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                if(!string.IsNullOrEmpty(user))
                    predicateGroup.Predicates.Add(Predicates.Field<OperRecord>(f => f.UserName, Operator.Eq, user));
                if(from!=null)
                    predicateGroup.Predicates.Add(Predicates.Field<OperRecord>(f => f.OperTime, Operator.Ge, from));
                if(to!=null)
                    predicateGroup.Predicates.Add(Predicates.Field<OperRecord>(f => f.OperTime, Operator.Le, to));
                IList<ISort> sort = new List<ISort>();
                sort.Add(new Sort { PropertyName = "OperTime", Ascending = false });
                IEnumerable<OperRecord> operRecords = result?.Connection.GetList<OperRecord>(predicateGroup, sort);
                return operRecords?.ToList();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }
      
    }
    public sealed class OperRecordMapper : ClassMapper<OperRecord>
    {
        public OperRecordMapper()
        {
            Table("user_oper_record");
            Map(x => x.Id).Key(KeyType.Assigned);
            //Ignore this property entirely
            //optional, map all other columns
            AutoMap();
        }
    }
}
